import * as API_Members from '../../../api/members.js'
import * as API_Goods from '../../../api/goods.js'
const app = getApp()
let log = require('../../../log.js') // 引用上面的log.js文件

Page({
    data: {
      defaultFace:'https://localhost/images/icon-noface.png',
      userInfo: {},
      // 默认未登录
      hasLogin: false,
      // 默认不显示
      showWxAuth: false,
      hideAuth: false,
      // 订单统计
      orderCount: {
        order_confirm: 0,
        order_paid_off: 0,
        order_shipped: 0,
        order_comment: 0,
        order_after_service: 0
      },
      // 是否显示海报弹窗
      isShowPoster: false,
      posterImageUrl: '',
    },
    onShow: async function () {
      let userInfo = wx.getStorageSync('user') || {};
      if (userInfo.face === 'null') {
        userInfo.face = null;
      };
      this.setData({
        userInfo: userInfo
      });
      this.getAuth();
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作 
     */
    onPullDownRefresh: function () {
      this.getAuth();
      // 停止下拉[回弹]
      wx.stopPullDownRefresh();
    },
    async getAuth() {
      if (wx.getStorageSync('wxauth')) {
        if (wx.getStorageSync('refresh_token') && wx.getStorageSync('user')) {
          await app.getUserAllInfo();
          this.setData({
            hasLogin: true,
            showWxAuth: false,
            hideAuth: true
          });
          const { userInfo } = this.data;
          const userData = wx.getStorageSync('user');
          const distributData = wx.getStorageSync('distributor');
          const leaderData = wx.getStorageSync('leader');
          userInfo.face = userData.face;
          userInfo.showIdentity = (distributData && distributData.audit_status === 2) ? '分销团长' : (leaderData && leaderData.audit_status === 2) ? '自提站点' : '普通用户';
          this.setData({
            userInfo
          });
          this.getMyView();
          // 获取分享时需要绑定的key
          app.getShareKey('pages/index-group/index/index', 'shareGrouping');
        } else {
          this.setData({
            hasLogin: false,
            showWxAuth: true,
            hideAuth: false
          });
        };
      };
    },
    isLogin() {
      if (!wx.getStorageSync('refresh_token')) {
        // 如果未授权 进行授权
        if (!wx.getStorageSync('wxauth')) {
          this.setData({
            hasLogin: false,
            showWxAuth: false
          });
          wx.navigateTo({ url: '/pages/auth/login/login' })
        } else {
          this.setData({
            showWxAuth: true,
            hideAuth: false
          })
        };
      } else {
        return true
      }
    },
    goUserInfo() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/my-profile/my-profile" })
    },
    // 获取汇总数据
    getMyView() {
      API_Members.getMyView().then(async res => {
        let { prompt } = res;
         // 订单汇总
        this.setData({
          orderCount: prompt
        });
      });
    },
    // 我的资料
    goProfile(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/my-profile/my-profile" })
    },
    // 全部订单
    goOrder() {
      if(!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/order/order" })
    },
    // 待付款订单
    payment(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/order/order?order_status=WAIT_PAY" })
    },
    // 待发货订单
    shipped() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/order/order?order_status=WAIT_SHIP" })
    },
    // 待收货订单
    received() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/order/order?order_status=WAIT_ROG" })
    },
    // 待评论订单
    commented(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/order/order?order_status=WAIT_COMMENT" })
    },
    // 退款/售后
    goAftersale(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/after-sale/after-sale'})
    },
    // 收货地址
    goAddress() {
      if(!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/address/address" })
    },
    // 积分管理
    goPoints(){
      if (!this.isLogin()) return
      wx.navigateTo({url: '/pages/ucenter/my-points/my-points'})
    },
    // 收藏夹
    goCollect() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/my-collect/my-collect" })
    },
    // 浏览足迹
    goFootprint(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/my-footprint/my-footprint'})
    },
    // 分销管理
    goDistribution(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: '/pages/spread/index/index' })  
    },
    // 我的钱包
    goWallet(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/wallet/wallet" })
    },
    // 多退少补
    goReturn() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/more-return/more-return" })
    },
    // 优惠券
    goCoupon() {
      if (!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/my-coupon/my-coupon" })
    },
    // 联系客服
    goContact(e) {
      console.log(e);
    },
    // 账户安全
    goAccountSafe(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/accountSafe/accountSafe"})
    },
    // 我的团长
    goMyLeader() {
      if(!this.isLogin()) return
      wx.navigateTo({ url: "/pages/ucenter/my-leader/my-leader" })
    },
    // 分享
    goShare() {
      if (!this.isLogin()) return
      wx.showLoading({
        title: '海报生成中...',
        icon: 'loading',
        duration: 8000
      });
      let _shareKey = wx.getStorageSync('shareGrouping') || '';
      let _params = {
        'page_type': 0, // 1:商品详情；2:微页面；0:无额外数据请求
        'page_path': 'pages/index-group/index/index',
        'scene': `${_shareKey}`
      };
      // 获取海报需要显示的信息
      API_Goods.getSunCode(_params).then(res => {
        if (res.sun_code_url && res.sun_code_url.indexOf('http:') > -1) {
          res.sun_code_url = `https:${res.sun_code_url.split('http:')[1]}`;
        };
        this.createNewImg(res);
      });
    },
    // 将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
    createNewImg(posterData) {
      const that = this;
      let headUrl = '';
      let codeUrl = '';
      const { sun_code_url } = posterData;
      const { face, nickname } = this.data.userInfo;
      let _urlArr = [
        {
          url: face || that.data.defaultFace,
          type: 1
        },
        {
          url: sun_code_url,
          type: 2
        }
      ];
      _urlArr.forEach(item => {
        if (item.url && item.url.indexOf('http:') > -1) {
          item.url = `https:${item.url.split('http:')[1]}`;
        };
        wx.downloadFile({
          url: item.url,
          success: function (res) {
            if (res.statusCode === 200) {
              let _urlNeed = res.tempFilePath;
              if (item.type === 1) {
                headUrl = _urlNeed;
              } else if (item.type === 2) {
                codeUrl = _urlNeed;
              };
              if (headUrl && codeUrl) {
                let context = wx.createCanvasContext('canvasPoster');
                context.setFillStyle('#ffffff');
                context.fillRect(0, 0, 320, 450);
                // 好友推荐
                context.setFontSize(15),
                context.setFillStyle('#2a2a2a');
                context.fillText(`好友 [${nickname}] 向你推荐`, 60, 37, 212);
                // 好友推荐
                context.setFontSize(10),
                context.setFillStyle('#909090');
                context.fillText('我发现一个物美价廉的团购平台，快来看看吧~', 60, 53, 212);
                // 模块分割线
                context.lineWidth = 0.5;
                context.translate(0.5, 0.5);
                context.moveTo(0, 66);
                context.lineTo(320, 66);
                context.strokeStyle = '#c6c6c6';
                context.stroke();
                // 太阳码
                context.drawImage(codeUrl, 60, 115, 200, 200);
                // 团购优惠
                const _blodText = '团购优惠·限时秒杀·好礼领不停';
                context.setFontSize(16),
                context.setFillStyle('#f62d4c');
                // context.fillText(_blodText, 54.5, 374.5, 230);
                // context.fillText(_blodText, 55, 374.5, 230);
                context.fillText(_blodText, 55, 375, 230);
                context.fillText(_blodText, 55.5, 375, 230);
                context.fillText(_blodText, 55, 375.5, 230);
                context.restore();
                // 长按识别查看
                context.setFontSize(12),
                context.setFillStyle('#818181');
                context.fillText('长按识别太阳码查看', 115, 398, 111);
                // 头像
                context.save();
                context.beginPath();
                context.arc(37, 37, 17, 0, Math.PI * 2);
                context.setFillStyle('white');
                context.fill();
                context.clip();
                context.drawImage(headUrl, 20, 20, 34, 34);
                context.restore();
                // 绘图
                context.draw(false, setTimeout(() => {
                  wx.canvasToTempFilePath({
                    canvasId: 'canvasPoster',
                    success: function (response) {
                      let tempFilePath = response.tempFilePath;
                      that.setData({
                        posterImageUrl: tempFilePath,
                        isShowPoster: true
                      });
                    },
                    fail: function (err) {
                      console.log(err);
                      log.error(err);
                    },
                    complete: function () {
                      wx.hideLoading()
                    }
                  })
                }, 500));
              };
            };
          },
          fail: function (error) {
            console.log(error);
            log.error(error);
          }
        });
      });
    },
    // 保存到相册
    savePoster() {
      var that = this;
      wx.saveImageToPhotosAlbum({
        filePath: that.data.posterImageUrl,
        success(res) {
          wx.showModal({
            content: '图片已保存到相册，赶紧晒一下吧~',
            showCancel: false,
            confirmText: '好的',
            confirmColor: '#333',
            success: function (res) {
              if (res.confirm) {
                console.log('用户点击确定');
                /* 关闭海报弹层 */
                that.closePoster();
              }
            }, fail: function (res) {
              console.log('保存失败')
            }
          })
        }
      })
    },
    // 关闭海报弹层
    closePoster() {
      this.setData({
        isShowPoster: false
      });
    },
    // 站内消息
    goMessage(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/site-message/site-message' })
    },
    // 资询管理
    goAsk(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/my-ask/my-ask' })
    },
    // 我的评论
    goComments(){
      if(!this.isLogin()) return
      wx.navigateTo({url: '/pages/ucenter/my-comments/my-comments'})
    },
    // 我的发票
    goReceipt(){
      if(!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/my-receipt/my-receipt'})
    },
    //增票资质
    goIncreaseTicket(){
      if (!this.isLogin()) return
      wx.navigateTo({ url: '/pages/ucenter/increase-ticket/increase-ticket'})
    },
    // 退出登录
    exitLogin() {
      API_Members.getUserInfo().then(response =>{
        if(response){
          wx.showModal({
            title: '提示',
            confirmColor: '#f42424',
            content: '确定要退出登录吗？这将会解绑您的微信！',
            success(res) {
              if (res.confirm) {
                API_Members.logout().then(() => {
                  wx.removeStorageSync('access_token')
                  wx.removeStorageSync('refresh_token')
                  wx.removeStorageSync('uid')
                  wx.removeStorageSync('user')
                  wx.switchTab({ url: '/pages/index/index' })
                }).catch()
              }
            }
          })
        }
      })
    }
  })
